package
{

public class Relative
{
	public var x:Number;
	public var y:Number;
	public var link:Collection;
	
	
	public function Relative(x:Number,y:Number)
	{
		this.x=x;
		this.y=y;
		link=new Collection();
	}
	
	public function addLink(rel:Relative):void{
		var index:int=getNewIndex(rel);
		link.addItemAt(rel,index);
		//var index2:int=rel.getNewIndex(this);
		//rel.link.addItemAt(this,index2);
	}
	
	public function getNewIndex(rel):int{
		//loop though current data and return when is larger degree
		var itr:Iterator=new Iterator(link.toArray());
		var item:Relative;
		var deg:Number=getDegree(rel);
		
		while(itr.hasNext()){
			item=itr.next() as Relative;
			if(deg<getDegree(item)){
				return itr.currentIndex()-1;
			}
		}
		
		return itr.currentIndex();
	}
	
	
	
	public function shortenStart(pos:Object,degree:Number):Object{
		var rad:Number=degree*Math.PI/180;
		var r:Number=20;
		var tx:Number;
		var ty:Number;
		
		tx=pos.x+r*Math.cos(rad);
		ty=pos.y-r*Math.sin(rad);
		
		return {x:tx,y:ty};
	}
	
	public function outputLinks():String{
		var itr:Iterator=new Iterator(link.toArray());
		var item:Relative;
		var str:String="";
		while(itr.hasNext()){
			item=itr.next() as Relative;
			str+="index:"+itr.currentIndex()+", "+item.x+","+item.y+"\n";
		}
		return str;
	}
	
	//get degree to the relative
	public function getDegree(rel:Object):Number{
		var x1:Number=this.x;
		var x2:Number=rel.x;
		var y1:Number=this.y;
		var y2:Number=rel.y;
		
		y1*=-1;
		y2*=-1;
		
		var angle:Number = Math.atan2(y2 - y1, x2 - x1) * (180 / Math.PI);
		return angle < 0 ? angle + 360 : angle;
	}
	
	public function getDistance(rel:Relative):Number{
		var dx:Number=rel.x-this.x;
		var dy:Number=rel.y-this.y;

		return Math.sqrt(dx*dx+dy*dy);
	}

	
}

}

